﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Simple.Common.Authentication;
using Simple.Repository.Models.Article;
using Simple.Repository.Models.ClassRoom;
using Simple.Repository.Models.Market;
using Simple.Services.System.Article.Model;
using Simple.Services.System.FileInfo;
using Simple.Services.System.Market.Models;

namespace Simple.Services.System.Market
{
    /// <summary>
    /// 商城相关
    /// </summary>
    public class MarketService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;
        private readonly FileInfoService _fileInfoService;

        public MarketService(SimpleDbContext context,
            ISimpleService services,
            FileInfoService fileInfoService) : base(services)
        {
            _context = context;
            _fileInfoService = fileInfoService;
        }

        /// <summary>
        /// 获取商品分类
        /// </summary>
        /// <returns></returns>
        public async Task<List<CommodityCategoryModel>> GetCommodityCategories()
        {
            var result = new List<CommodityCategoryModel>();

            var lstClass = (await OrganizationFilter(_context.Set<CommodityCategory>().AsQueryable())).ToList();

            return MapperHelper.Map<List<CommodityCategoryModel>>(lstClass);
        }

        /// <summary>
        /// 商品分类详细数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CommodityCategoryModel> GetCommodityCategorieyAsync(Guid? categoryId)
        {
            if (!categoryId.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,商品分类Id参数不能为Null!");
            }

            var info = await _context.Set<CommodityCategory>().FirstOrDefaultAsync(c => c.Id == categoryId);

            if (info == null)
            {
                throw AppResultException.Status409Conflict("未找到商品分类相关数据!");
            }

            var outResult = MapperHelper.Map<CommodityCategoryModel>(info);
            return outResult;
        }

        /// <summary>
        /// 添加商品分类
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> AddCommodityCategorieyAsync(CommodityCategoryModel model)
        {
            if (await _context.Set<CommodityCategory>().AnyAsync(m => m.TypeName == model.TypeName))
            {
                throw AppResultException.Status409Conflict("已存在相同商品分类，请重新填写！");
            }

            var classRoom = MapperHelper.Map<CommodityCategory>(model);
            await _context.AddAsync(classRoom);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 修改商品分类
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> UpdateCommodityCategorieyAsync(CommodityCategoryModel model)
        {
            if (!model.Id.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,商品分类Id参数不能为Null!");
            }

            if (await _context.Set<CommodityCategory>().AnyAsync(m => m.Id != model.Id && m.TypeName == model.TypeName))
            {
                throw AppResultException.Status409Conflict("已存在相同商品分类，请重新填写！");
            }

            var info = await _context.Set<CommodityCategory>()
                .FirstOrDefaultAsync(m => model.Id == m.Id);

            MapperHelper.Map(model, info);
            _context.Update(info);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        /// <summary>
        /// 删除商品分类
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteCommodityCategorieyAsync(List<Guid?> ids)
        {
            if (ids == null || !ids.Any())
            {
                throw AppResultException.Status409Conflict("参数错误,商品分类Id参数不能为Null!");
            }

            var infos = await _context.Set<CommodityCategory>()
                .Where(m => ids.Contains(m.Id))
                .ToListAsync();

            if (infos == null || !infos.Any())
            {
                throw AppResultException.Status404NotFound("未找到商品分类相关数据，删除失败！");
            }

            var cInfos = _context.Set<Commodity>().Where(c => ids.Contains(c.CategoryId))?.ToList();
            if (cInfos != null && cInfos.Any())
            {
                throw AppResultException.Status404NotFound($"商品[{string.Join(",", cInfos.Select(c => c.Title))}]已关联分类，删除失败！");
            }

            // 先更新数据库
            _context.RemoveRange(infos);
            int ret = await _context.SaveChangesAsync();
            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task<CommodityModel> GetCommodityAsync(Guid? commodityId)
        {
            if (!commodityId.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,商品Id参数不能为Null!");
            }

            var commodityInfo = await _context.Set<Commodity>().Include(c => c.CategoryInfo).Include(c => c.Images)
                .Where(c => c.Id == commodityId)
                .FirstOrDefaultAsync();

            if (commodityInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到相关商品数据!");
            }

            var outResult = MapperHelper.Map<CommodityModel>(commodityInfo);
            return outResult;
        }

        /// <summary>
        /// 商品分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResultModel<CommodityModel>> GetCommodityPageAsync(CommodityPageQueryModel input)
        {
            var result = new PageResultModel<CommodityModel>();
            var query = await OrganizationFilter(_context.Set<Commodity>().Include(c => c.Images).Include(c => c.CategoryInfo));

            if (!string.IsNullOrEmpty(input.Title))
            {
                query = query.Where(m => EF.Functions.Like(m.Title, $"%{input.Title}%"));
            }

            if (input.CategoryId.HasValue)
            {
                query = query.Where(m => m.CategoryId == input.CategoryId);
            }

            // 排序
            query = query.OrderByDescending(m => m.CreatedTime);

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.Page(input.PageNo, input.PageSize);
            var resultList = await query.ToListAsync();
            result.Rows = MapperHelper.Map<List<CommodityModel>>(resultList);

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> AddCommodityAsync(CommodityCreateOrUpdateModel model)
        {
            if (model == null)
            {
                throw AppResultException.Status409Conflict("参数不能为Null!");
            }

            var images = new List<CommodityImage>();
            if (model.ImageList != null && model.ImageList.Any())
            {
                foreach (var file in model.ImageList)
                {
                    var fileId = await _fileInfoService.UploadAsync(new FileInfo.Models.FileInfoInputModel { BusinessType = FileSource.Market, File = file });
                    images.Add(new CommodityImage { FiledId = fileId, FileName = file.FileName, FileSize = GetFileSize(file.Length) });
                }
            }

            if (model.CategoryId.HasValue)
            {
                var category = await GetCommodityCategorieyAsync(model.CategoryId);
                if (category == null)
                {
                    throw AppResultException.Status409Conflict("找不到商品分类数据!");
                }
            }

            var articleManageInfo = MapperHelper.Map<Commodity>(model);
            articleManageInfo.Images = images;
            await _context.AddAsync(articleManageInfo);
            return await _context.SaveChangesAsync();
        }
        private string GetFileSize(long size)
        {
            var num = 1024.00;
            if (size < num)
                return size + " B";
            if (size < Math.Pow(num, 2))
                return (size / num).ToString("f2") + " KB";
            if (size < Math.Pow(num, 3))
                return (size / Math.Pow(num, 2)).ToString("f2") + " MB";
            if (size < Math.Pow(num, 4))
                return (size / Math.Pow(num, 3)).ToString("f2") + " GB";
            return (size / Math.Pow(num, 4)).ToString("f2") + " TB";
        }

        /// <summary>
        /// 修改商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> UpdateCommodityAsync(CommodityCreateOrUpdateModel model)
        {
            if (!model.Id.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,商品Id参数不能为Null!");
            }

            var cInfo = await _context.Set<Commodity>().Include(c => c.Images)
                .FirstOrDefaultAsync(m => model.Id == m.Id);

            if (cInfo == null)
            {
                throw AppResultException.Status404NotFound("未找到商品相关数据，更新失败！");
            }

            if (model.CategoryId.HasValue)
            {
                var category = await GetCommodityCategorieyAsync(model.CategoryId);
                if (category == null)
                {
                    throw AppResultException.Status409Conflict("找不到文章分类数据!");
                }
            }

            if (cInfo?.Images != null && cInfo.Images.Any())
            {
                _context.RemoveRange(cInfo.Images);
            }

            var images = new List<CommodityImage>();
            if (model.ImageList != null && model.ImageList.Any())
            {
                foreach (var file in model.ImageList)
                {
                    var fileId = await _fileInfoService.UploadAsync(new FileInfo.Models.FileInfoInputModel { BusinessType = FileSource.Market, File = file });
                    images.Add(new CommodityImage { FiledId = fileId, FileName = file.FileName, FileSize = GetFileSize(file.Length) });
                }

                if (images != null && images.Any())
                {
                    cInfo.Images = images;
                }
            }

            cInfo.Content = model.Content;
            cInfo.CategoryId = model.CategoryId;
            cInfo.Title = model.Title;
            cInfo.IsShow = model.IsShow;
            cInfo.StockCount=model.StockCount;
            cInfo.Integral=model.Integral;

            _context.Update(cInfo);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteCommodityAsync(List<Guid?> ids)
        {
            if (ids == null || !ids.Any())
            {
                throw AppResultException.Status409Conflict("参数错误,商品Id参数不能为Null!");
            }

            var resultList = await _context.Set<Commodity>().Include(c => c.Images)
                .Where(m => ids.Contains(m.Id))
                .ToListAsync();

            if (resultList == null || !resultList.Any())
            {
                throw AppResultException.Status404NotFound("未找到商品相关数据，删除失败！");
            }

            // 先更新数据库
            _context.RemoveRange(resultList);
            int ret = await _context.SaveChangesAsync();
            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }



    }
}
